//
//  ZZTimer.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/8/11.
//

import UIKit

class ZZTimer {
    
    deinit {
        invalidate()
    }
    
    init(_ queue: DispatchQueue) {
        timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
    }
    
    private let timer: DispatchSourceTimer
    
    private var validTimer = false
    
    private var isPaused = false
    
    func scheduled(repeat interval: Double, qos: DispatchQoS, event: @escaping () -> ()) {
        timer.schedule(deadline: .now(), repeating: interval)
        timer.setEventHandler(qos: qos, flags: [], handler: event)
    }
    
    func fire() {
        guard !validTimer else {
            restart()
            return
        }
        timer.resume()
        validTimer = true
    }
    
    func pause() {
        guard validTimer, !isPaused else {
            return
        }
        timer.suspend()
        isPaused = true
    }
    
    func restart() {
        guard validTimer, isPaused else {
            return
        }
        timer.resume()
        isPaused = false
    }
    
    private func invalidate() {
        if validTimer {
            if isPaused {
                timer.resume()
            }
            timer.cancel()
        } else {
            timer.resume()
            timer.cancel()
        }
    }
}
